package com.base.cn.platform.os.controller.web.order.pay;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.op.ActivityCodeCondition;
import com.base.cn.platform.os.entity.order.order.OrderCondition;
import com.base.cn.platform.os.entity.order.order.OrderType;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.op.activity.OpActivityService;
import com.base.cn.platform.os.service.manage.order.goods.OrderService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import com.base.cn.platform.os.service.manage.user.address.CusUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @describe 订单支付
 * @auther s.li
 * @date 2019/6/5 16:07
 */
@Controller
@RequestMapping("/web/uc/order")
public class WebPayOrderController extends WebBaseController {

    @Autowired
    private CusUserAccountService cusUserAccountService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CusUserAddressService cusUserAddressService;
    @Autowired
    private OpActivityService opActivityService;

    /**
     * 重新支付订单
     * @param orderId 订单ID
     * @return
     */
    @RequestMapping("/newlyOrder")
    public String newlyOrder(HttpServletRequest request,
                             Model model,
                             @RequestParam("orderId") BigDecimal orderId){
        OrderCondition condition = new OrderCondition();
        condition.setId(orderId);
        condition.setSetUserData(false);
        condition.setSetDetailsData(true);
        condition.setSetShopData(true);
        condition.setSetOrderBook(true);
        Map<String,Object> order = orderService.findOrderInfo(condition);
        model.addAttribute("buyNum",order.get("buyNum"));
        model.addAttribute("order",order);
        if(OrderType.COMMON.getKey().equals(order.get("orderType").toString())){
            BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
            //获取用户的账户
            Map<String,Object> userAccount = cusUserAccountService.userAccountInfo(userId,false);
            if ("ACTIVE".equalsIgnoreCase(userAccount.get("accountStatus").toString())) {
                model.addAttribute("userAccount",userAccount);
            }
        }

        //获取支付配置
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
        model.addAttribute("configMap",configMap);

        return resultPage("/order/goods/newly-order");
    }

    /**
     * 前台生成免费订单
     * @param request HttpServletRequest
     * @param payType 支付类型，MEMBER,FREE目前只支持两种
     * @param shopData 商品数据包
     * @return Map<String,Object>
     */
    @RequestMapping("/genFreeOrder")
    @ResponseBody
    public Map<String,Object> genFreeOrder(HttpServletRequest request,
                                           @RequestParam("payType") String payType,
                                           @RequestParam("shopData") String shopData){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> orderDataFrom = new HashMap<>();
        orderDataFrom.put("userId",userId);
        orderDataFrom.put("shopData",shopData);
        orderDataFrom.put("payType",payType);
        orderDataFrom.put("orderForm",OrderSource.ORDER_FORM_WEB);
        return orderService.createWebFreeOrder(orderDataFrom);
    }

    /**
     * 创建支付订单
     * @return
     */
    @RequestMapping("/createPayOrder")
    @ResponseBody
    public Map<String,Object> createPayOrder(HttpServletRequest request,
                                             @RequestBody Map<String,Object> orderDataFrom){
        orderDataFrom.put("userId",webMobileLoginUtil.getLoginUserId(request));
        orderDataFrom.put("orderForm", OrderSource.ORDER_FORM_WEB);
        Map<String,Object> resultMap = orderService.createPayOrder(orderDataFrom);
        //得到订单对象
        Map<String,Object> order = (Map<String,Object>) ResultUtil.getEntity(resultMap);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        String orderStatus = (String)order.get("orderStatus");
        String url;
        if(orderStatus.equals(OrderStatus.SUCCESS)){//如果订单已经支付成功
            url = "/web/pay/payMessage?orderNo="+order.get("orderNo")+"&type=2";
        }else {//如果订单未支付成功
            String payType = (String)orderDataFrom.get("payType");
            String orderType = (String)orderDataFrom.get("orderType");
            url = "/web/uc/pay/gotoPay?payType="+payType+"&orderNo="+order.get("orderNo")+"&orderType="+orderType;
            if(orderType.equals(OrderType.ACCOUNT.getKey())){
                double sumPrice = Double.parseDouble(order.get("sumPrice").toString());
                url+="&price="+Math.abs(sumPrice);
            }
        }
        resultMap.put("url",url);
        return resultMap;
    }

    /**
     * 初始化订单页面
     * @param request HttpServletRequest
     * @param orderType 订单类型
     * @param shopData 商品包
     * @return
     */
    @RequestMapping("/initPayOrder")
    public String initPayOrder(HttpServletRequest request,
                               Model model,
                               @RequestParam("orderType") String orderType,
                               @RequestParam(value = "shopData",required = false) String shopData){

        model.addAttribute("orderType",orderType);
        model.addAttribute("shopData",shopData);
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        if(orderType.equals(OrderType.COMMON.getKey())){
            //获取用户的账户
            Map<String,Object> userAccount = cusUserAccountService.userAccountInfo(userId,false);
            if ("ACTIVE".equalsIgnoreCase(userAccount.get("accountStatus").toString())) {
                model.addAttribute("userAccount",userAccount);
            }
        }

        //获取支付配置
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
        model.addAttribute("configMap",configMap);

        return resultPage("/order/pay/init-pay-order");
    }


    /**
     * 获取支付页面的商品
     * @param request HttpServletRequest
     * @param orderType 订单类型
     * @param shopData 商品数据
     * @param activityId 活动ID
     * @param couponCode 优惠券编码
     * @return Map<String,Object>
     */
    @RequestMapping("/getPayOrderShopList")
    @ResponseBody
    public Map<String,Object> getPayOrderShopList(HttpServletRequest request,
                                                  @RequestParam("orderType") String orderType,
                                                  @RequestParam(value = "shopData",required = false) String shopData,
                                                  @RequestParam(value = "activityId",required = false,defaultValue = "0") BigDecimal activityId,
                                                  @RequestParam(value = "couponCode",required = false) String couponCode){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> params = new HashMap<>();
        params.put("orderType",orderType);
        params.put("shopData",shopData);
        params.put("activityId",activityId);
        params.put("code",couponCode);
        params.put("userId",userId);
        return orderService.getPayOrderShopList(params);
    }

    /**
     * 获取用户收货地址
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/findUserAddressList")
    public String findUserAddressList(Model model,
                                     HttpServletRequest request){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String,Object>> userAddressList = cusUserAddressService.queryUserAddressListByUserId(userId,true);
        model.addAttribute("userAddressList",userAddressList);
        return resultPage("/order/goods/ajax-user-address-list");
    }

    /**
     * 查询订单可使用的优惠券和活动数据
     * @param request HttpServletRequest
     * @param paramsList  查询条件
     * @return  Map<String,Object>
     */
    @RequestMapping("/findOrderAvailableActivityAndCode")
    @ResponseBody
    public Map<String,Object> findOrderAvailableActivityAndCode(HttpServletRequest request,
                                                                @RequestParam("filterActivity") boolean filterActivity,
                                                                @RequestParam("filterCode") boolean filterCode,
                                                                @RequestBody List<Map<String,String>> paramsList){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        ActivityCodeCondition condition = new ActivityCodeCondition();
        condition.setFilterActivity(filterActivity);
        condition.setFilterCode(filterCode);
        condition.setUserId(userId);
        condition.setParamsList(paramsList);
        return opActivityService.findOrderAvailableActivityAndCode(condition);
    }

}
